package com.ws.eduservice.controller;


import com.ws.commonutils.R;
import com.ws.eduservice.client.VodClient;
import com.ws.eduservice.entity.EduVideo;
import com.ws.eduservice.service.EduVideoService;
import com.ws.servicebase.exceptionhandler.MyException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author ws
 * @since 2024-12-04
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;

    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo video) {
        boolean save = videoService.save(video);
        if(!save){
            return R.error().message("添加小节失败");
        }
        return R.ok();
    }

    @GetMapping("getVideo/{id}")
    public R getVideoById(@PathVariable("id") String id) {
        EduVideo video = videoService.getById(id);
        return R.ok().data("video", video);
    }

    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo video) {
        boolean b = videoService.updateById(video);
        if(!b){
            return R.error().message("更新小节失败");
        }
        return R.ok();
    }

    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable("id") String id) {

        EduVideo video = videoService.getById(id);
        String videoSourceId = video.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            R result = vodClient.deleteVideo(videoSourceId);
            if(result.getCode()==20001){
                throw new MyException(20001,"删除视频失败，熔断器");
            }
        }

        boolean b = videoService.removeById(id);
        if(!b){
            return R.error().message("删除小节失败");
        }
        return R.ok();
    }


}

